<template>
  <div class="login">
      <div class="login_box">
          <div class="avatar">
              <img src="../assets/heima.png" alt="">
          </div>
          <!-- 利用ref可以拿到表单组件 -->
          <el-form ref="loginForm" class="login_form" :model="form" :rules="loginFormRules">
            <el-form-item prop="username">
                <el-input v-model="form.username" prefix-icon="iconfont icon-user"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="form.password" prefix-icon="iconfont icon-3702mima" type="password"></el-input>
            </el-form-item>
            <el-form-item class="bottom_btn">
                <el-button type="primary" @click="login">登录</el-button>
                <el-button type="info" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
      </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: 'admin',
        password: '123456'
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
  },

  methods: {
    resetForm () {
      this.$refs.loginForm.resetFields()
    },
    login () {
      this.$refs.loginForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('/login', this.form)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('登陆成功')
        sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.login{
    width: 100%;
    height: 100%;
    background: #2b4b6b;

    .login_box{
        width: 450px;
        height: 300px;
        background: #fff;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        border-radius: 5px;

        .avatar{
            width: 100px;
            height: 100px;
            border-radius: 50%;
            box-shadow: 0 0 10px #ddd;
            padding: 10px;
            background: #fff;
            position: absolute;
            top: -50px;
            left: 50%;
            transform: translate(-50%);

            img{
                width: 100%;
                height: 100%;
            }
        }
        .login_form{
          margin-top: 100px;
          padding: 0 20px;
          .bottom_btn{
            display: flex;
            justify-content: flex-end;
          }
        }
    }
}
</style>
